<?php

namespace api\modules\v1\controllers;

use services\api\AccessTokenService;
use Yii;
use yii\web\HttpException;
use common\helpers\ImageHelper;
use common\helpers\CommonHelper;
use common\models\member\Member;
use common\models\member\Attr;
use services\member\MemberService;
use api\controllers\OnAuthController;
use api\modules\v1\forms\member\MemberForm;

/**
 * 用户接口
 *
 * Class MemberController
 * @package api\modules\v1\controllers\member
 */
class MemberController extends OnAuthController
{
    public $modelClass = Member::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $optional = [];

    /**
     * @api {get} /v1/member/permissions 1.0.1 获取用户权限信息
     * @apiName permissions
     * @apiGroup 10Member
     *
     * @apiParam {Number} project_id 项目ID
     *
     * @apiSuccess {Number} defaultProjectId        默认项目ID
     * @apiSuccess {Array}  auth                    权限列表
     * @apiSuccess {Array}  auth.header             模块列表
     * @apiSuccess {Array}  auth.sider              菜单列表
     * @apiSuccess {Array}  auth.action             动作列表
     * @apiSuccess {Array}  project                 项目列表
     * @apiSuccess {Number} is_role_kf              是否绑定客服角色【1是、0否】
     * @apiSuccess {Number} is_role_yz              是否绑定医助角色【1是、0否】
     * @apiSuccess {Number} is_nurse                是否绑定护士角色【1是、0否】
     *
     */
    public function actionPermissions()
    {
        $projectId = Yii::$app->request->get('project_id', 0);
        $member = Yii::$app->user->identity->member;
        return Yii::$app->services->member->memberPerssions($member['id'], $member['is_super'], $projectId);
    }

    /**
     * @api get /v1/member/index 名称
     * @apiGroup member
     * @apiName 获取部门下的人
     * @apiVersion 1.0.0
     *
     * @apiDescription 获取部门下的人，非超管只能看到当前操作者所在的部门下人员

     * @param int profession_id 岗位id
     * @param int department_id 部门id
     * @param int role_id 角色id
     * @param int keyword 搜索关键词
     * @param int status 状态
     *
     * @apiSuccess {Number} code    状态码，200：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @return array
     */
    public function actionIndexMember()
    {
        $member = Yii::$app->user->identity->member;
        $params = Yii::$app->request->get();
        $departmentLeaderId = intval($params['department_leader_id'] ?? 0);
        $professionId = intval($params['profession_id'] ?? 0);
        $departmentId = intval($params['department_id'] ?? 0);
        $roleId = intval($params['role_id'] ?? 0);
        $keyword = trim($params['keyword'] ?? '');
        $status = $params['status'] ?? null;
        $limit = intval($params['pageSize'] ?? $this->limit);
        $page = intval($params['page'] ?? 1);
        $projectId = intval($params['project_id'] ?? 0);
        // $memberDepartmentId = (int) Attr::find()->where(['member_id' => Yii::$app->user->identity->member_id])->select('department_id')->scalar();
        if ($member['is_super'] == Member::IS_SUPER_NO) {
            // 如果当前操作者不是超管， 查看的部门不是自己当前所在的部门， 则直接返回空数据
            return ['list' => [], 'total' => 0, 'pageSize' => $limit, 'page' => $page];
        }
        $params = [
            'department_leader_id' => $departmentLeaderId,
            'profession_id' => $professionId,
            'department_id' => $departmentId,
            'role_id' => $roleId,
            'keyword' => $keyword,
            'status' => $status,
            'limit' => $limit,
            'page' => $page,
            'projectId' => $projectId,
        ];

        return MemberService::getList($params);
    }

    /**
     * @api {get} /v1/member/info 获取用户信息
     * @apiName info
     * @apiGroup Member
     *
     *
     * @apiSuccess {Object}  data                       返回数据
     * @apiSuccess {Number}  data.member_id             用户UID
     * @apiSuccess {String}  data.realname              姓名
     * @apiSuccess {Number}  data.mobile                手机号
     * @apiSuccess {Number}  data.gender                性别【0未知、1男、2女】
     * @apiSuccess {String}  data.head_img_url          头像url
     * @apiSuccess {Number}  data.profession_id         岗位ID
     * @apiSuccess {String}  data.profession_name       岗位名称
     * @apiSuccess {Number}  data.project_id            项目ID
     * @apiSuccess {String}  data.project_name          项目名称
     *
     */
    public function actionInfo()
    {
        // 用户信息
        $member = Yii::$app->user->identity->member;

        // 用户属性
        $attr = Yii::$app->services->attr->findInfo([
            'member_id' => Yii::$app->user->identity->member_id,
            'project_id' => $this->projectId,
        ]);

        // 项目信息
        $project = Yii::$app->services->project->findById($this->projectId);

        return [
            'member_id' => $member->id,
            'realname' => $member->realname,
            'mobile' => $member->mobile,
            'gender' => $member->gender,
            'head_img' => $member->head_img,
            'head_img_url' => $member->head_img ? ImageHelper::getImagePathUrl($member->head_img) : '',
            'profession_id' => $attr->profession_id ?? 0,
            'profession_name' => $attr->profession_name ?? '',
            'project_id' => $project->id ?? 0,
            'project_name' => $project->name ?? '',
            'is_bind_dingtalk' => $member->ding_unionid ? 1 : 0,
        ];
    }

    /**
     * @api post /v1/member
     * @apiGroup member
     * @apiName 新增人员
     * @apiVersion 1.0.0
     *
     * @apiDescription 新增人员 (超管專用)

     * @param string name 姓名
     * @param string mobile 手机号
     * @param int profession_id 岗位id
     * @param int profession_name 岗位名称
     * @param string password 密码，不传默认123456
     *
     * @apiSuccess {Number} code    状态码，200：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @return array
     * @throws HttpException
     */
    public function actionCreateMember()
    {
        $params = Yii::$app->request->post();
        $name = trim($params['name'] ?? '');
        $mobile = trim($params['mobile'] ?? '');
//        $professionId = intval($params['profession_id'] ?? 0);
//        $professionName = trim($params['profession_name'] ?? '');
        $departmentId = intval($params['department_id'] ?? 0);
        $is_department_leader = intval($params['is_department_leader'] ?? Attr::IS_DEPARTMENT_LEADER_NO);
        $password = trim($params['password'] ?? '');
        $password_re = trim($params['password_re'] ?? '');

        if ($password != $password_re) {
            throw new HttpException(422, '两次密码不一致,请确认密码');
        }
        $project_id = $params['project_id'] ?? '';
//        $role_id = $params['role_id'];
        $user_name = trim($params['user_name'] ?? '');
        $status = intval($params['status'] ?? Member::STATUS_INVALID);
        $gender = intval($params['gender'] ?? Member::GENDER_UNKNOW);
        $password = $password ? : '123456';

        if (!$name || !$mobile) {
            throw new HttpException(422, '新增失败，基本信息不能为空！');
        }

        // 判断手机号是否唯一
        $memberExists = Member::find()->where(['mobile' => $mobile])->andWhere(['!=', 'status', Member::STATUS_DELETE])->exists();
        if ($memberExists) {
            throw new HttpException(422, '新增失败，手机号已存在！');
        }

        try {
            $data = [
                'name' => $name,
                'user_name' => $user_name,
                'mobile' => $mobile,
//                'professionId' => $professionId,
                'department_id' => $departmentId,
                'project_id' => explode(',', $project_id),
//                'role_id' =>  array_filter(explode(',', $role_id)),
                'status' => $status,
                'gender' => $gender,
//                'professionName' => $professionName,
                'password_hash' => Yii::$app->security->generatePasswordHash($password),
                'auth_key' => Yii::$app->security->generateRandomString(),
                'is_department_leader' => $is_department_leader,
                'password' => $password,
            ];
            $res = MemberService::createMember($data);
        } catch (\Exception $exception) {
            throw new HttpException(500, $exception->getMessage());
        }

        return $res;
    }

    /**
     * @api post /v1/member/update-member
     * @apiGroup member
     * @apiName 编辑用户信息
     * @apiVersion 1.0.0
     *
     * @apiDescription 编辑用户信息

     * @param int id
     * @param string name 姓名
     * @param string mobile 手机号
     * @param string password 密码，传空则不修改
     * @param int profession_id 岗位id
     * @param string profession_name 岗位名称
     * @param string role_ids 角色id集合
     * @param int status 状态
     *
     * @apiSuccess {Number} code    状态码，200：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @return array
     * @throws HttpException
     * @throws \yii\base\Exception
     */
    public function actionUpdateMember()
    {
        $params = Yii::$app->request->post();
        $id = intval($params['id'] ?? 0);
        $name = trim($params['name'] ?? '');
        $user_name = trim($params['user_name'] ?? '');
        $mobile = trim($params['mobile'] ?? '');
        $password = trim($params['password'] ?? '');
        $password_re = trim($params['password_re'] ?? '');

        if ($password != $password_re) {
            throw new HttpException(422, '两次密码不一致,请确认密码');
        }
        $project_id = $params['project_id'] ?? '';
//        $professionId = trim($params['profession_id'] ?? 0);
        $departmentId = intval($params['department_id'] ?? 0);
        $gender = intval($params['gender'] ?? Member::GENDER_UNKNOW);
//        $professionName = trim($params['profession_name'] ?? '');
//        $roleIds = trim($params['role_id'] ?? '');
        $status = intval($params['status'] ?? Member::STATUS_INVALID);
        $is_department_leader = intval($params['is_department_leader'] ?? Attr::IS_DEPARTMENT_LEADER_NO);
        if (!$name || !$mobile) {
            throw new HttpException(422, '修改失败，姓名或手机号不能为空！');
        }

        // 判断id对应的信息是否存在
        $memberExists = Member::find()->where(['id' => $id])->exists();

        if (!$memberExists) {
            throw new HttpException(422, '编辑失败，对应的id不存在！');
        }

        // 判断手机号是否已存在
        $mobileExists = Member::find()->where(['mobile' => $mobile])->andWhere(['!=', 'id', $id])->andWhere(['!=', 'status', Member::STATUS_DELETE])->exists();
        if ($mobileExists) {
            throw new HttpException(422, '编辑失败，该手机号已存在！');
        }

        $data = [
            'name' => $name,
            'user_name' => $user_name,
            'gender' => $gender,
            'mobile' => $mobile,
            'project_id' =>  explode(',', $project_id),
            'department_id' => $departmentId,
            'password_hash' => $password ? Yii::$app->security->generatePasswordHash($password) : '',
//            'professionId' => $professionId,
//            'professionName' => $professionName,
//            'roleIdData' =>  array_filter(explode(',', $roleIds)),
            'status' => $status,
            'is_department_leader' => $is_department_leader,
            'password' => $password,
        ];

        try {
            $res = MemberService::updateMember($data, $id);
        } catch (\Exception $exception) {
            throw new HttpException($exception->getCode(), $exception->getMessage());
        }

        return $res;
    }

    /**
     * @api post /v1/member/update-status-member
     * @apiGroup member
     * @apiName 编辑用户状态
     * @apiVersion 1.0.0
     *
     * @apiDescription 编辑用户状态
     * @param int status 状态
     *
     * @apiSuccess {Number} code    状态码，200：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @return array
     * @throws HttpException
     * @throws \yii\base\Exception
     */
    public function actionUpdateStatusMember()
    {
        $params = Yii::$app->request->post();
        $id = $params['id'];
        $status = $params['status'] ? Member::STATUS_ENABLE : Member::STATUS_INVALID;
        $model = Member::findOne($id);
        $model->status = $status;
        if (!$model->save()) {
            return CommonHelper::api(422, '状态切换失败');
        }

        MemberService::changeCount($model->id);

        if ($status == Member::STATUS_INVALID) {
            AccessTokenService::clearMemberToken($id);
        }

        return CommonHelper::api(200, 'success');
    }

    /**
     * @api post /v1/member/role-list
     * @apiGroup member
     * @apiName 项目下的角色,关联
     * @apiVersion 1.0.0
     *
     * @apiDescription 项目下的角色,关联
     * @param int status 状态
     *
     * @apiSuccess {Number} code    状态码，200：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @return array
     * @throws HttpException
     * @throws \yii\base\Exception
     */
    public function actionRoleList()
    {
        $project_id = Yii::$app->request->get('project_id');
        return MemberService::roleList($project_id);
    }

    /**
     * @api {post} /v1/member/update-info 更新用户信息
     * @apiName update-info
     * @apiGroup Member
     *
     * @apiParam {String} realname                      姓名
     * @apiParam {Number} mobile                        手机
     * @apiParam {Number} gender                        性别
     * @apiParam {String} head_img                      头像
     *
     * @apiSuccess {Object}  data                       返回数据
     * @apiSuccess {Number}  data.member_id             用户UID
     *
     */
    public function actionUpdateInfo()
    {
        $params = Yii::$app->request->post();
        $params['id'] = Yii::$app->user->identity->member_id;

        $model = new MemberForm();
        $model->setScenario('edit');
        $model->attributes = $params;
        if (!$model->validate()) {
            // 返回数据验证失败
            return CommonHelper::api(422, $this->getError($model));
        }

        return Yii::$app->services->member->updateInfo($model);
    }

    /**
     * @api {post} /v1/member/update-password 更改密码
     * @apiName update-password
     * @apiGroup Member
     *
     * @apiParam {String} password                      原密码
     * @apiParam {String} new_password                  新密码
     * @apiParam {String} confirm_password              确认密码
     *
     * @apiSuccess {Object}  data                       返回数据
     * @apiSuccess {Number}  data.member_id             用户UID
     *
     */
    public function actionUpdatePassword()
    {
        $params = Yii::$app->request->post();
        $params['id'] = Yii::$app->user->identity->member_id;

        $model = new MemberForm();
        $model->setScenario('edit_password');
        $model->attributes = $params;
        if (!$model->validate()) {
            // 返回数据验证失败
            return CommonHelper::api(422, $this->getError($model));
        }

        return Yii::$app->services->member->updatePassword($model);
    }
}
